package com.gjt.downFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * Created with Intel IDEA.
 * 文件下载
 *
 * @Auther: gjt
 * @Date: 2024/7/5 21:18
 */
public class batchRemove {

    public static void main(String[] args) {


//    String urlStr = "https://gzc-dfsdown.mail.ftn.qq.com/1373//xtfd2148-c422-62b1-3739-ac4d791a4eca?dkey=5cKA6brCIZ7CqFWIb6sijCMYIVxqChsIQbSuyPhLbCSGOtsXEUv1W2WZZJ8uPfNDpkSxh80ME57Kz9yP3hGuTxg&fname=Summary.tar.gz&eggs";
        String urlStr = "http://152.136.138.218/data/1.txt";
//        String urlStr = "https://down.qishu66.com/d/file/down/2022/11/12/仙草供应商.txt";
//        String urlStr = "https://tse1-mm.cn.bing.net/th/id/OIP-C.2rQ25qnSMQHXGcHz3Rp2pAAAAA?w=303&h=189&c=7&r=0&o=5&dpr=1.3&pid=1.7";
        try {
            // 网络资源的URL地址
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setRequestMethod("POST");
            connection.setRequestMethod("GET");
            // 设置请求超时和读取超时，可选
            connection.setConnectTimeout(10000); // 连接超时时间，单位毫秒
            connection.setReadTimeout(10000);
            connection.setRequestProperty("Charset", CHARSET);
            long contentLength = connection.getContentLength();
            Map<String, List<String>> headerFields = connection.getHeaderFields();

            headerFields.entrySet().stream().forEach(entry -> System.out.println("key : " + entry.getKey() + " value : " + entry.getValue().toString()));
//            int responseCode = connection.getResponseCode();
//
//            if(responseCode != 200) {System.out.println("请求失败，响应码：" + responseCode); }
            // 从连接获取输入流
            try (InputStream in = connection.getInputStream()) {

                File file = new File("D:\\新建文件夹\\");
                if(!file.exists()){
                    file.mkdirs();
                }

                String format = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
                FileOutputStream fileOutputStream = new FileOutputStream(file.getPath() + File.separator +format+ "tmp.txt");
                byte[] bytes = new byte[1024];
                int c ;
                while (( c=in.read(bytes)) != -1) {
                    fileOutputStream.write(bytes,0,bytes.length);
                    fileOutputStream.flush();
                }
                fileOutputStream.close();
                System.out.println("下载完成");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }


}
